package stark.app.function.netusage;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;

import com.blankj.utilcode.constant.MemoryConstants;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.stark.netusage.lib.AppLimitService;
import com.stark.netusage.lib.AppNetUsageInfo;
import com.stark.netusage.lib.NetUsageUtil;
import com.stark.netusage.lib.db.AppLimitDbHelper;
import com.stark.netusage.lib.db.AppLimitInfo;

import androidx.recyclerview.widget.LinearLayoutManager;
import stark.app.R;
import stark.app.databinding.ActivityAppUsageDetailBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.constant.Extra;
import stark.common.basic.inf.IRetCallback;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.TimeUtil;

/**
 * Author：daizhongbin on 2022/8/11
 * Email：1027154338@qq.com
 * Desc:
 */
public class AppUsageDetailActivity extends BaseNoModelActivity<ActivityAppUsageDetailBinding> {

    private String mPckName;
    private NetUsageDateAdapter mDateAdapter;

    public static void start(Context context, String pckName) {
        Intent intent = IntentUtil.getIntent(context, AppUsageDetailActivity.class);
        intent.putExtra(Extra.DATA, pckName);
        context.startActivity(intent);
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_app_usage_detail;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        mPckName = intent.getStringExtra(Extra.DATA);
        if (TextUtils.isEmpty(mPckName)) {
            return;
        }

        mDataBinding.ivIcon.setImageDrawable(AppUtils.getAppIcon(mPckName));
        mDataBinding.tvAppName.setText(AppUtils.getAppName(mPckName));
        AppLimitInfo appLimitInfo = AppLimitDbHelper.getByPckName(mPckName);
        if (appLimitInfo != null) {
            mDataBinding.tvAddLimit.setText("已加入");
        } else {
            mDataBinding.tvAddLimit.setText("加入流量监控");
            mDataBinding.tvAddLimit.setOnClickListener(v -> {
                if (hasPermission()) {
                    AppLimitInfo limitInfo = new AppLimitInfo();
                    limitInfo.pckName = mPckName;
                    //这里因为只是示范，所以直接写死为每日流量使用不超过50m
                    limitInfo.setLimitBytes(50 * MemoryConstants.MB);
                    AppLimitDbHelper.insert(limitInfo);
                    AppLimitService.start(AppUsageDetailActivity.this);
                    mDataBinding.tvAddLimit.setText("已加入");
                    mDataBinding.tvAddLimit.setOnClickListener(null);
                }
            });
        }

        mDataBinding.rvUsages.setLayoutManager(new LinearLayoutManager(this));
        mDateAdapter = new NetUsageDateAdapter();
        mDataBinding.rvUsages.setAdapter(mDateAdapter);
    }

    @Override
    protected void initData() {
        getAppTodayUsage();
        getApp7DaysUsage();
    }

    private boolean hasPermission() {
        boolean hasPermission = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            hasPermission = PermissionUtils.isGrantedDrawOverlays();
            if (!hasPermission) {
                PermissionUtils.requestDrawOverlays(null);
            }
        }
        return hasPermission;
    }

    private void getAppTodayUsage() {
        long endTime = System.currentTimeMillis();
        long startTime = TimeUtil.getStartOfOneDay(endTime);
        NetUsageUtil.getInPeriod(mPckName, startTime, endTime, new IRetCallback<AppNetUsageInfo>() {
            @Override
            public void onResult(AppNetUsageInfo result) {
                String mobile = ConvertUtils.byte2FitMemorySize(result.getMobileTotalBytes(), 1);
                mDataBinding.tvMobileData.setText(mobile);
                int progress = (int) (result.getMobileTotalBytes() * 1f / result.getTotalBytes() * 100);
                mDataBinding.pbMobile.setProgress(progress);

                String wifi = ConvertUtils.byte2FitMemorySize(result.getWifiTotalBytes(), 1);
                mDataBinding.tvWifiData.setText(wifi);
                progress = (int) (result.getWifiTotalBytes() * 1f / result.getTotalBytes() * 100);
                mDataBinding.pbWifi.setProgress(progress);
            }
        });
    }

    private void getApp7DaysUsage() {
        long endTime = TimeUtil.getStartOfToday();
        long startTime = TimeUtil.getStartOfOneDay(endTime - 7 * TimeConstants.DAY);
        NetUsageUtil.getInPeriod(mPckName, startTime, endTime, new IRetCallback<AppNetUsageInfo>() {
            @Override
            public void onResult(AppNetUsageInfo result) {
                mDateAdapter.setNewInstance(result.usageInfos);
            }
        });
    }


}
